package me.zhengjie.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

public class IpUtils {

    private static final List<String> IP_HEADERS = Arrays.asList(
        "X-Forwarded-For",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "X-Real-IP"
    );

    public static String getClientIp(HttpServletRequest request) {
        for (String header : IP_HEADERS) {
            String value = request.getHeader(header);
            if (value != null && !value.isEmpty() && !"unknown".equalsIgnoreCase(value)) {
                if (header.equals("X-Forwarded-For")) {
                    return value.split(",")[0].trim();
                }
                return value;
            }
        }
        return request.getRemoteAddr();
    }

    public static String getRemoteIp(HttpServletRequest request) {
        HttpServletRequest httpServletRequest = RequestHolder.getHttpServletRequest();
        return httpServletRequest.getRemoteHost();
    }
}